import axios, { AxiosInstance } from "axios";
import config from "./config";
import { getSession } from "./storage";

class Request {
  baseURL: string;
  timeout: number;
  constructor() {
    this.baseURL = config.baseServerURL;
    this.timeout = 3000;
  }

  getToken=()=>{return `Bearer ${getSession("access_token")}`;}

  mergeOptions(options?: any) {
    return {
      baseURL: this.baseURL,
      timeout: this.timeout,
      ...options,
    };
  }

  setInterceptors(instance: AxiosInstance) {
    instance.interceptors.request.use(
      (config) => {
        config.headers={
          Authorization : this.getToken(),
          post:{
            "Content-Type":"application/json;charset=UTF-8"
          }
        };
        return config;
      },
      (err) => Promise.reject(err)
    );

    instance.interceptors.response.use(
      (response) => response.data,
      (err) => Promise.reject(err)
    );
  }

  request(options?: any) {
    const instance = axios.create();
    const opts = this.mergeOptions(options);
    this.setInterceptors(instance);
    return instance(opts);
  }

  get(url: string, config?: any) {
    return this.request({
      url,
      method: "GET",
      ...config,
    });
  }

  post(url: string, data?: any) {
    return this.request({
      url,
      method: "POST",
      data,
    });
  }


}

let request= new Request();
window.http= request;// set window
export default request;

